/**
 *
 * @param money 金额,数字或者字符串
 * @param fractionDigits 保留小数,默认都保留
 * @returns
 */

import { roundNumber } from "./roundNumber";

export type IParseMoneyFn = (
  money?: number | string,
  fractionDigits?: number,
  needRegExp?: boolean,
  needTrim?: boolean
) => string;

export const parseMoney: IParseMoneyFn = (
  money,
  fractionDigits = -1,
  needRegExp = true,
  needTrim = true
) => {
  if (!money) {
    return "0";
  }
  if (typeof money !== "string") {
    money = String(money);
  }

  const isNeedFixed = fractionDigits && fractionDigits >= 0;
  let moneyFixed = money;
  if (isNeedFixed) {
    moneyFixed = roundNumber(money, fractionDigits, needTrim);
  }

  if (!needRegExp) {
    return moneyFixed;
  }
  const isNegativeNumber = moneyFixed[0] == "-";
  if (!isNegativeNumber) {
    return moneyFixed.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  } else {
    return "-" + moneyFixed.slice(1).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
  }
};
